<template>
    <div class="user-management">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>用户管理</span>
                    <el-button type="primary" @click="showAddDialog = true">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加用户
                    </el-button>
                </div>
            </template>

            <!-- 搜索区域 -->
            <div class="search-section">
                <el-form :model="searchForm" inline>
                    <el-form-item label="用户名">
                        <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
                    </el-form-item>
                    <el-form-item label="角色">
                        <el-select v-model="searchForm.role" placeholder="请选择角色" clearable>
                            <el-option label="管理员" value="admin" />
                            <el-option label="用户1" value="yonghu1" />
                            <el-option label="用户2" value="yonghu2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">
                            <el-icon>
                                <Search />
                            </el-icon>
                            搜索
                        </el-button>
                        <el-button @click="handleReset">
                            <el-icon>
                                <Refresh />
                            </el-icon>
                            重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 用户列表 -->
            <el-table :data="filteredUserList" v-loading="loading" border>
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="username" label="用户名" width="120" />
                <el-table-column prop="name" label="姓名" width="120" />
                <el-table-column prop="avatar" label="头像" width="100">
                    <template #default="{ row }">
                        <el-avatar :src="row.avatar" :size="40" />
                    </template>
                </el-table-column>
                <el-table-column prop="roles" label="角色" width="120">
                    <template #default="{ row }">
                        <el-tag v-for="role in row.roles" :key="role" type="primary" size="small">
                            {{ role }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="permissions" label="权限" min-width="200">
                    <template #default="{ row }">
                        <el-tag v-for="permission in row.permissions" :key="permission" type="success" size="small"
                            style="margin-right: 5px;">
                            {{ permission }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="handleEdit(row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="handleDelete(row)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-section">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[5, 10, 20, 50]" :total="totalUsers" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 添加/编辑用户对话框 -->
        <el-dialog v-model="showAddDialog" :title="isEdit ? '编辑用户' : '添加用户'" width="500px">
            <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="userForm.name" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="!isEdit">
                    <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item label="角色" prop="roles">
                    <el-select v-model="userForm.roles" multiple placeholder="请选择角色">
                        <el-option label="管理员" value="admin" />
                        <el-option label="用户1" value="yonghu1" />
                        <el-option label="用户2" value="yonghu2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="权限" prop="permissions">
                    <el-select v-model="userForm.permissions" multiple placeholder="请选择权限">
                        <el-option label="全部权限" value="*" />
                        <el-option label="demo:read" value="demo:read" />
                        <el-option label="demo:write" value="demo:write" />
                    </el-select>
                </el-form-item>
                <el-form-item label="头像" prop="avatar">
                    <el-input v-model="userForm.avatar" placeholder="请输入头像URL" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="showAddDialog = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitting">
                    {{ isEdit ? '更新' : '添加' }}
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { useUser } from "@/store/user.js";
import { Plus, Search, Refresh, Edit, Delete } from "@element-plus/icons-vue";

const userStore = useUser();

// 响应式数据
const loading = ref(false);
const showAddDialog = ref(false);
const isEdit = ref(false);
const submitting = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const userFormRef = ref();

// 搜索表单
const searchForm = reactive({
    username: "",
    role: ""
});

// 用户表单
const userForm = reactive({
    username: "",
    name: "",
    password: "",
    roles: [],
    permissions: [],
    avatar: ""
});

// 表单验证规则
const userRules = {
    username: [
        { required: true, message: "请输入用户名", trigger: "blur" }
    ],
    name: [
        { required: true, message: "请输入姓名", trigger: "blur" }
    ],
    password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        { min: 6, message: "密码长度不能少于6位", trigger: "blur" }
    ],
    roles: [
        { required: true, message: "请选择角色", trigger: "change" }
    ],
    permissions: [
        { required: true, message: "请选择权限", trigger: "change" }
    ]
};

// 计算属性
const totalUsers = computed(() => userStore.totalUsers);
const filteredUserList = computed(() => {
    let list = userStore.userList;

    // 应用搜索过滤
    if (searchForm.username) {
        list = list.filter(user =>
            user.username.toLowerCase().includes(searchForm.username.toLowerCase())
        );
    }

    if (searchForm.role) {
        list = list.filter(user => user.roles.includes(searchForm.role));
    }

    // 分页
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return list.slice(start, end);
});

// 方法
const loadUserList = async () => {
    loading.value = true;
    try {
        await userStore.getUserList();
    } catch (error) {
        ElMessage.error("加载用户列表失败");
    } finally {
        loading.value = false;
    }
};

const handleSearch = () => {
    currentPage.value = 1;
};

const handleReset = () => {
    searchForm.username = "";
    searchForm.role = "";
    currentPage.value = 1;
};

const handleEdit = (row) => {
    isEdit.value = true;
    Object.assign(userForm, {
        ...row,
        password: "" // 编辑时不显示密码
    });
    showAddDialog.value = true;
};

const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除用户 "${row.name}" 吗？`,
            "确认删除",
            {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }
        );

        await userStore.deleteUser(row.id);
        ElMessage.success("删除成功");
    } catch (error) {
        if (error !== "cancel") {
            ElMessage.error("删除失败");
        }
    }
};

const handleSubmit = async () => {
    try {
        await userFormRef.value.validate();
        submitting.value = true;

        if (isEdit.value) {
            await userStore.updateUser(userForm.id, userForm);
            ElMessage.success("更新成功");
        } else {
            await userStore.addUser(userForm);
            ElMessage.success("添加成功");
        }

        showAddDialog.value = false;
        resetForm();
    } catch (error) {
        if (error !== false) { // 表单验证失败时error为false
            ElMessage.error(isEdit.value ? "更新失败" : "添加失败");
        }
    } finally {
        submitting.value = false;
    }
};

const resetForm = () => {
    Object.assign(userForm, {
        username: "",
        name: "",
        password: "",
        roles: [],
        permissions: [],
        avatar: ""
    });
    isEdit.value = false;
    userFormRef.value?.resetFields();
};

const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
};

// 监听对话框关闭
watch(showAddDialog, (newVal) => {
    if (!newVal) {
        resetForm();
    }
});

// 生命周期
onMounted(() => {
    loadUserList();
});
</script>

<style lang="scss" scoped>
.user-management {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-section {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f5f5f5;
    border-radius: 8px;
}

.pagination-section {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.el-table {
    margin-bottom: 20px;
}

.el-tag {
    margin-right: 5px;
}
</style>
